//
//  File.swift
//  正则表达式相关辅助方法
//
//  Created by smile on 2019/5/24.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

class RegUtil {
    
    /// 匹配mention的正则表达式
    /// ？表示禁用贪婪模式，详细的请参考《详解正则表达式》课程
    static let REG_MENTION = "@([\\u4e00-\\u9fa5a-zA-Z0-9_-]{2,30})"
    
    /// 匹配hashTag的正则表达式
    static let REG_HASH_TAG = "#(.*?)#"
    
    
    /// 查找Mentions
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    static func findMentions(_ data:String) -> [NSTextCheckingResult] {
        return find(REG_MENTION,data)
    }
    
    /// 查找HashTag
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    static func findHashTag(_ data:String) -> [NSTextCheckingResult] {
        return find(REG_HASH_TAG,data)
    }
    
    /// 使用指定的正则表达式从字符串中查找匹配的信息
    /// 返回找到的结果
    ///
    /// - Parameters:
    ///   - reg: <#reg description#>
    ///   - data: <#data description#>
    /// - Returns: <#return value description#>
    static func find(_ reg:String,_ data:String) -> [NSTextCheckingResult] {
        //创建一个正则表达式匹配对象
        let mentionResultsRegular = try! NSRegularExpression(pattern: reg, options: NSRegularExpression.Options.caseInsensitive)
        
        //调用匹配方法
        return mentionResultsRegular.matches(in:data,options:[],range: NSRange(location: 0, length: data.count))
    }
}
